const express = require('express');
const router = express.Router();
const pool = require('../db');
const authMiddleware = require('../middleware/authMiddleware'); // 导入验证中间件

// 获取帖子列表
router.get('/posts', authMiddleware, async (req, res) => {
    try {
        const userId = req.user.id;  // 获取当前用户ID
        const [posts] = await pool.query('SELECT * FROM posts'); // 获取所有帖子
        const [likedPosts] = await pool.query('SELECT post_id FROM post_likes WHERE user_id = ?', [userId]);
        const [favoritedPosts] = await pool.query('SELECT post_id FROM post_favorites WHERE user_id = ?', [userId]);

        // 获取用户已点赞和已收藏的帖子 ID 列表
        const likedPostIds = likedPosts.map(post => post.post_id);
        const favoritedPostIds = favoritedPosts.map(post => post.post_id);

        res.json({
            posts: posts,
            likedPosts: likedPostIds, // 返回用户已点赞的帖子 ID 列表
            favoritedPosts: favoritedPostIds, // 返回用户已收藏的帖子 ID 列表
        });
    } catch (err) {
        console.error('Error fetching posts:', err); // 详细日志
        res.status(500).json({ success: false, message: '获取帖子失败', error: err.message });
    }
});

// 点赞帖子 - 添加验证中间件
router.post('/posts/:id/like', authMiddleware, async (req, res) => {
    const userId = req.user.id;  // 获取当前登录用户的 ID
    const postId = req.params.id;

    try {
        // 检查用户是否已点赞该帖子
        const [existingLike] = await pool.query('SELECT * FROM post_likes WHERE user_id = ? AND post_id = ?', [userId, postId]);
        if (existingLike.length > 0) {
            return res.status(400).json({ message: '您已经点赞过该帖子' });
        }

        // 插入点赞记录
        await pool.query('INSERT INTO post_likes (user_id, post_id) VALUES (?, ?)', [userId, postId]);
        await pool.query('UPDATE posts SET likes = likes + 1 WHERE id = ?', [postId]);

        res.json({ success: true, message: '点赞成功' });
    } catch (err) {
        res.status(500).json({ success: false, message: '点赞失败', error: err.message });
    }
});

// 取消点赞 - 添加验证中间件
router.post('/posts/:id/unlike', authMiddleware, async (req, res) => {
    const userId = req.user.id;
    const postId = req.params.id;

    try {
        // 检查用户是否已经点赞
        const [existingLike] = await pool.query('SELECT * FROM post_likes WHERE user_id = ? AND post_id = ?', [userId, postId]);
        if (existingLike.length === 0) {
            return res.status(400).json({ message: '您尚未点赞该帖子' });
        }

        // 删除点赞记录
        await pool.query('DELETE FROM post_likes WHERE user_id = ? AND post_id = ?', [userId, postId]);
        await pool.query('UPDATE posts SET likes = likes - 1 WHERE id = ?', [postId]);

        res.json({ success: true, message: '取消点赞成功' });
    } catch (err) {
        res.status(500).json({ success: false, message: '取消点赞失败', error: err.message });
    }
});

// 收藏帖子 - 添加验证中间件
router.post('/posts/:id/favorite', authMiddleware, async (req, res) => {
    const userId = req.user.id;  // 获取当前用户ID
    const postId = req.params.id;

    try {
        // 检查用户是否已收藏
        const [existingFavorite] = await pool.query('SELECT * FROM post_favorites WHERE user_id = ? AND post_id = ?', [userId, postId]);
        if (existingFavorite.length > 0) {
            return res.status(400).json({ message: '您已经收藏过该帖子' });
        }

        // 插入收藏记录
        await pool.query('INSERT INTO post_favorites (user_id, post_id) VALUES (?, ?)', [userId, postId]);
        await pool.query('UPDATE posts SET favorites = favorites + 1 WHERE id = ?', [postId]);

        res.json({ success: true, message: '收藏成功' });
    } catch (err) {
        res.status(500).json({ success: false, message: '收藏失败', error: err.message });
    }
});

// 取消收藏 - 添加验证中间件
router.post('/posts/:id/unfavorite', authMiddleware, async (req, res) => {
    const userId = req.user.id;  // 获取当前用户ID
    const postId = req.params.id;

    try {
        // 检查用户是否已收藏
        const [existingFavorite] = await pool.query('SELECT * FROM post_favorites WHERE user_id = ? AND post_id = ?', [userId, postId]);
        if (existingFavorite.length === 0) {
            return res.status(400).json({ message: '您尚未收藏该帖子' });
        }

        // 删除收藏记录
        await pool.query('DELETE FROM post_favorites WHERE user_id = ? AND post_id = ?', [userId, postId]);
        await pool.query('UPDATE posts SET favorites = favorites - 1 WHERE id = ?', [postId]);

        res.json({ success: true, message: '取消收藏成功' });
    } catch (err) {
        res.status(500).json({ success: false, message: '取消收藏失败', error: err.message });
    }
});

// 获取用户点赞和收藏状态
router.get('/posts/status', authMiddleware, async (req, res) => {
    const userId = req.user.id;
    try {
        const [likedPosts] = await pool.query('SELECT post_id FROM post_likes WHERE user_id = ?', [userId]);
        const [favoritedPosts] = await pool.query('SELECT post_id FROM post_favorites WHERE user_id = ?', [userId]);

        res.json({
            likedPosts: likedPosts.map(post => post.post_id),
            favoritedPosts: favoritedPosts.map(post => post.post_id),
        });
    } catch (err) {
        res.status(500).json({ success: false, message: '获取用户状态失败', error: err.message });
    }
});

module.exports = router;